﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using SubSonic;
using LinFen;
using System.Data.SqlClient;

public partial class webUserControl_SearchSupplier : System.Web.UI.UserControl
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if(!IsPostBack)
        {
           
            Query _q = new Query("customerinfo");
            _q.AddWhere("ID", Request["cID"]);
            IDataReader _dr = _q.ExecuteReader();
            if(_dr.Read())
            {
                lbloutDate.Text = Convert.ToDateTime(_dr["outTime"].ToString()).ToShortDateString();
                lblInDate.Text = Convert.ToDateTime(_dr["intime"].ToString()).ToShortDateString();
            }
            AddItems(DDLcatalog,"sysCatalog","0",0);
            AddItems(ddlDangCi,"sysDangci","0",0);
            //HyperLink1.NavigateUrl = "~/myPoints.aspx?cid=" + Request["ID"];

            Cookies aCookies = new Cookies();
            int flag = int.Parse(aCookies.getCookies("cFlag"));
            int isType = int.Parse(aCookies.getCookies("cisType"));
            int districtID = int.Parse(aCookies.getCookies("cDistrictID"));
            int cityID = int.Parse(aCookies.getCookies("cCityID"));

            if (flag == 1)
            {
                AddItems(DDLcityID, "sysCityName", cityID.ToString(), 0);
                DDLDistrictID.Items.Clear();
                Query q = new Query("sysDistrictName");
                q.AddWhere("cityid", DDLcityID.SelectedValue);
                IDataReader dr = q.ExecuteReader();
                while (dr.Read())
                {
                    ListItem li = new ListItem();
                    li.Value = dr[0].ToString();
                    li.Text = dr[1].ToString();
                    DDLDistrictID.Items.Add(li);
                }
            }

            if (flag == 0)
            {
                AddItems(DDLcityID, "sysCityName", cityID.ToString(), 0);
                DDLcityID.Enabled = false;

                DDLDistrictID.Items.Clear();
                Query q = new Query("sysDistrictName");
                q.AddWhere("cityid", DDLcityID.SelectedValue);
                IDataReader dr = q.ExecuteReader();
                ListItem _li = new ListItem("全部显示", "0");
                DDLDistrictID.Items.Add(_li);
                while (dr.Read())
                {
                    ListItem li = new ListItem();
                    li.Value = dr[0].ToString();
                    li.Text = dr[1].ToString();
                    DDLDistrictID.Items.Add(li);
                }
            }
        }
        CustomerDataBind();
    }
    protected void GridView2_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        Literal1.Text = "";
        if (e.CommandName == "shifang")
        {
            int oID = int.Parse(e.CommandArgument.ToString());
            StoredProcedure sp = new StoredProcedure("sp_ExcuteOrderSingle");
            sp.Command.AddParameter("@oID", oID);
            sp.Execute();
            Query q = new Query("orderinfo");
            q.AddWhere("ID", oID);
            IDataReader dr = q.ExecuteReader();
            if (dr.Read())
            {
                int NumMale = int.Parse(dr[3].ToString());
                int NumFeMale = int.Parse(dr[4].ToString());
                int NumHongGan = int.Parse(dr[5].ToString());
                int NumBaoJian = int.Parse(dr[6].ToString());
                int NumQiTa = int.Parse(dr[7].ToString());
                SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["LinFen"].ConnectionString);
                SqlCommand cmd = new SqlCommand();
                cmd.CommandType = CommandType.Text;
                cmd.Connection = conn;
                cmd.CommandText = "update customerinfo set isOKPoint = isOKPoint -" +
                                  (NumQiTa + NumMale + NumHongGan + NumFeMale + NumBaoJian) + " where id=" + dr[1];
                conn.Open();
                cmd.ExecuteNonQuery();
                OrderInfo.Delete("ID", oID);
                conn.Close();
                Literal1.Text = "<script language=javascript>alert('分配释放成功！');</script>";
            }
            
            GridView2.DataBind();
            CustomerDataBind();
            //Response.Redirect(Request.Url.ToString());
        }
    }
    static void AddItems(DropDownList ddl, string tb, string id, int isType)
    {
        if (isType == 1)
        {
            for (int i = 0; i <= 10; i++)
            {
                ListItem li = new ListItem();
                li.Value = i.ToString();
                li.Text = i.ToString();
                if (id == i.ToString())
                {
                    li.Selected = true;
                }
                ddl.Items.Add(li);
            }
        }
        else
        {
            Query q = new Query(tb);
            IDataReader dr = q.ExecuteReader();
            ListItem _li=new ListItem("全部显示","0");
            ddl.Items.Add(_li);
            while (dr.Read())
            {
                ListItem li = new ListItem();
                li.Value = dr[0].ToString();
                li.Text = dr[1].ToString();
                if (id == dr[0].ToString())
                {
                    li.Selected = true;
                }
                ddl.Items.Add(li);
            }
        }

    }
    protected void btnSub_Click(object sender, EventArgs e)
    {
        SearchBtnClick();
    }
    void CustomerDataBind()
    {
        int id = 0;
        if (Request["cid"] != null)
        {
            id = int.Parse(Request["cid"]);
        }
        SqlQuery q = new SqlQuery();
        q.From("vw_CustomerOrderSum");
        q.Where("customerid").IsEqualTo(id);
        IDataReader dr = q.ExecuteReader();
        if (dr.Read())
        {
            lbCustomerName.Text = dr["customername"].ToString();
            lbTelPhone.Text = dr["Telphone"].ToString();
            lbLinkMan.Text = dr["LinkMan"].ToString();
            lbYewu.Text = dr["YeWu"].ToString();
            lbAllPoints.Text = dr["istotalpoint"].ToString();
            lbSumPoints.Text = dr["isokPoint"].ToString();
            lbEndDate.Text = Convert.ToDateTime(dr["OutTime"].ToString()).ToShortDateString();
            lbFeMaleS.Text = dr["FemaleC"].ToString();
            lbManS.Text = dr["Malec"].ToString();
            lbHongGanS.Text = dr["hongganc"].ToString();
            lbBaoJianS.Text = dr["baojian"].ToString();
            lbQiTa.Text = dr["qitac"].ToString();
            
            lbSupplierC.Text = SupplierNum(id);
            if (dr["istotalpoint"].ToString() == dr["isokPoint"].ToString())
            {
                Response.Redirect("~/PointsListLoad.aspx?ID="+Request["cID"]);
            }
            if (dr["isStatus"].ToString() == "0")
            {
                btnFenPei.Enabled = false;
            }
            
        }
        else
        {
            bindCustomerInfoBak(id);
        }
    }
    void bindCustomerInfoBak( int id)
    {
        SqlQuery q = new SqlQuery();
        q.From("customerinfo");
        q.Where("id").IsEqualTo(id);
        IDataReader dr = q.ExecuteReader();
        if (dr.Read())
        {
            lbCustomerName.Text = dr["customername"].ToString();
            lbTelPhone.Text = dr["Telphone"].ToString();
            lbLinkMan.Text = dr["LinkMan"].ToString();
            lbYewu.Text = dr["YeWu"].ToString();
            lbAllPoints.Text = dr["istotalpoint"].ToString();
            lbSumPoints.Text = dr["isokPoint"].ToString();
            lbEndDate.Text = Convert.ToDateTime(dr["OutTime"].ToString()).ToShortDateString();
            lbFeMaleS.Text = "0";
            lbManS.Text = "0";
            lbHongGanS.Text = "0";
            lbBaoJianS.Text = "0";
            lbQiTa.Text = "0";
            lbSupplierC.Text = "0";
            if (dr["istotalpoint"].ToString() == dr["isokPoint"].ToString())
            {
                Response.Redirect("~/PointsListLoad.aspx?ID=" + Request["cID"]);
            }
            if(dr["isStatus"].ToString()=="0")
            {
                btnFenPei.Enabled = false;
            }

        }
    }
    void SearchBtnClick()
    {
        Literal1.Text = "";
        Panel1.Visible = true;
        SqlQuery q = new SqlQuery();
        q.From("vw_supplierinfodetail");
        q.AndExpression("TypeID").IsEqualTo(ddlIsType.SelectedValue);
        if (DDLcityID.SelectedValue!="0")
        {
            q.AndExpression("cityid").IsEqualTo(DDLcityID.SelectedValue);
        }
        if(DDLDistrictID.SelectedValue!="0")
        {
            q.AndExpression("districtID").IsEqualTo(DDLDistrictID.SelectedValue);
        }
        if (DDLcatalog.SelectedValue!="0")
        {
            q.AndExpression("catalogID").IsEqualTo(DDLcatalog.SelectedValue);
        }
        if (ddlDangCi.SelectedValue!="0")
        {
            q.AndExpression("dangciid").IsEqualTo(ddlDangCi.SelectedValue);
        }
            q.AndExpression("numready").IsGreaterThan(0);
        if(tbID.Text!="")
        {
        q.AndExpression("ID").IsEqualTo(tbID.Text);
        }
        if(tbSuppliername.Text !="")
        {
            q.AndExpression("suppliername").Like("%"+tbSuppliername.Text+"%");
        }
            GridView1.DataSource = q.ExecuteDataSet();
        GridView1.DataBind();
    }
    protected void btnFenPei_Click(object sender, EventArgs e)
    {
        Literal1.Text = "";
        if ((GridView1.SelectedIndex != -1))
        {
            int id = 0;
            if (Request["cid"] != null)
            {
                id = int.Parse(Request["cid"]);
            }
            int NumMale = int.Parse(DDLMale.SelectedValue);
            int NumFemale = int.Parse(DDLFemale.SelectedValue);
            int NumHongGan = int.Parse(DDLHongGan.SelectedValue);
            int NumBaoJian = int.Parse(DDLBaoJian.SelectedValue);
            int NumQiTa = int.Parse(DDLQiTa.SelectedValue);
            int _Points = int.Parse(lbAllPoints.Text) - int.Parse(lbSumPoints.Text) -
                          (NumMale + NumFemale + NumHongGan + NumBaoJian + NumQiTa);
            if (_Points >= 0)
            {
                Literal1.Text = "";
                int customerID = int.Parse(GridView1.SelectedValue.ToString());
                OrderInfo.Insert(id, customerID, NumMale, NumFemale, NumHongGan, NumBaoJian, NumQiTa,
                                 DateTime.Parse(lbloutDate.Text), "0",DateTime.Parse(lblInDate.Text));
                Query q = new Query("CustomerInfo");
                Query _q = new Query("customerinfo");
                _q.AddWhere("id", id);
                IDataReader _drq = _q.ExecuteReader();
                _drq.Read();
                q.AddUpdateSetting("isOkPoint",
                                   int.Parse(_drq["isOkpoint"].ToString()) + NumMale + NumFemale + NumHongGan +
                                   NumBaoJian +
                                   NumQiTa);
                q.AddWhere("id", id);
                q.Execute();

                Query query = new Query("SupplierInfo");
                query.AddWhere("ID", GridView1.SelectedValue.ToString());
                IDataReader dataReader = query.ExecuteReader();
                if (dataReader.Read())
                {
                    //dataReader.Read();
                    Query _query = new Query("supplierinfo");
                    _query.AddUpdateSetting("nummale", int.Parse(dataReader["nummale"].ToString()) - NumMale)
                        .AddUpdateSetting("numfemale", int.Parse(dataReader["numfemale"].ToString()) - NumFemale)
                        .AddUpdateSetting("numhonggan", int.Parse(dataReader["numhonggan"].ToString()) - NumHongGan)
                        .AddUpdateSetting("numbaojian", int.Parse(dataReader["numbaojian"].ToString()) - NumBaoJian)
                        .AddUpdateSetting("numqita", int.Parse(dataReader["numqita"].ToString()) - NumQiTa)
                        .AddUpdateSetting("numok",
                                          NumMale + NumFemale + NumHongGan + NumBaoJian + NumQiTa +
                                          int.Parse(dataReader["numok"].ToString()))
                        .AddUpdateSetting("numready",
                                          int.Parse(dataReader["numready"].ToString()) -
                                          (NumMale + NumFemale + NumHongGan + NumBaoJian + NumQiTa));
                    _query.AddWhere("id", GridView1.SelectedValue.ToString());
                    _query.Execute();
                    SearchBtnClick();
                    CustomerDataBind();
                    GridViewChange();
                    GridView1.SelectedIndex = -1;
                    GridView2.DataBind();
                    Literal1.Text = "<script language=javascript>alert('点位分配成功！');</script>";
                }
            }
            else
            {
                Literal1.Text = "<script language=javascript>alert('分配数额过多！请重新选择分配数额。');</script>";
            }
        }
        else
        {
            Literal1.Text = "<script language=javascript>alert('请选择投放地点！');</script>";
        }
    }
    protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
    {
        Literal1.Text = "";
        GridViewChange();
    }
    void GridViewChange()
    {
        int _NumMale = 0;
        int _NumFemale = 0;
        int _NumHongGan = 0;
        int _NumBaoJian = 0;
        int _NumQiTa = 0;

        int customerID = int.Parse(GridView1.SelectedValue.ToString());

        //Response.Write(customerID);
        SqlQuery q = new SqlQuery();
        q.From("supplierinfo");
        q.AndExpression("id").IsEqualTo(customerID);
        IDataReader dr = q.ExecuteReader();
        if (dr.Read())
        {
            _NumMale = int.Parse(dr["nummale"].ToString());
            _NumFemale = int.Parse(dr["numfemale"].ToString());
            _NumHongGan = int.Parse(dr["numhonggan"].ToString());
            _NumBaoJian = int.Parse(dr["numbaojian"].ToString());
            _NumQiTa = int.Parse(dr["NumQita"].ToString());
            DDLMale.Items.Clear();
            DDLFemale.Items.Clear();
            DDLHongGan.Items.Clear();
            DDLBaoJian.Items.Clear();
            DDLQiTa.Items.Clear();
            for (int i = 0; i <= _NumMale; i++)
            {
                ListItem li = new ListItem();
                li.Text = i.ToString();
                li.Value = i.ToString();
                DDLMale.Items.Add(li);
            }
            for (int i = 0; i <= _NumFemale; i++)
            {
                ListItem li = new ListItem();
                li.Text = i.ToString();
                li.Value = i.ToString();
                DDLFemale.Items.Add(li);
            }
            for (int i = 0; i <= _NumBaoJian; i++)
            {
                ListItem li = new ListItem();
                li.Text = i.ToString();
                li.Value = i.ToString();
                DDLBaoJian.Items.Add(li);
            }
            for (int i = 0; i <= _NumHongGan; i++)
            {
                ListItem li = new ListItem();
                li.Text = i.ToString();
                li.Value = i.ToString();
                DDLHongGan.Items.Add(li);
            }
            for (int i = 0; i <= _NumQiTa; i++)
            {
                ListItem li = new ListItem();
                li.Text = i.ToString();
                li.Value = i.ToString();
                DDLQiTa.Items.Add(li);
            }
        }
        else
        {
            Response.Write("no");
        }
    }
    protected void DDLcityID_SelectedIndexChanged(object sender, EventArgs e)
    {
        DDLDistrictID.Items.Clear();
        Query q = new Query("sysDistrictName");
        q.AddWhere("cityid", DDLcityID.SelectedValue);
        IDataReader dr = q.ExecuteReader();
        while (dr.Read())
        {
            ListItem li = new ListItem();
            li.Value = dr[0].ToString();
            li.Text = dr[1].ToString();
            DDLDistrictID.Items.Add(li);
        }
    }
    protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        Literal1.Text = "";
        Panel1.Visible = true;
        SqlQuery q = new SqlQuery();
        q.From("vw_supplierinfodetail");
        q.AndExpression("TypeID").IsEqualTo(ddlIsType.SelectedValue);
        if (DDLcityID.SelectedValue != "0")
        {
            q.AndExpression("cityid").IsEqualTo(DDLcityID.SelectedValue);
        }
        if (DDLDistrictID.SelectedValue != "0")
        {
            q.AndExpression("districtID").IsEqualTo(DDLDistrictID.SelectedValue);
        }
        if (DDLcatalog.SelectedValue != "0")
        {
            q.AndExpression("catalogID").IsEqualTo(DDLcatalog.SelectedValue);
        }
        if (ddlDangCi.SelectedValue != "0")
        {
            q.AndExpression("dangciid").IsEqualTo(ddlDangCi.SelectedValue);
        }
        if (tbID.Text != "")
        {
            q.AndExpression("ID").IsEqualTo(tbID.Text);
        }
        if (tbSuppliername.Text != "")
        {
            q.AndExpression("suppliername").Like("%" + tbSuppliername.Text + "%");
        }
        q.AndExpression("numready").IsGreaterThan(0);
        
        if (ViewState["sortColumn"]!= null)
        {
            if (ViewState["sortDirection"] == null)
            {
                ViewState["sortDirection"] = "ASC";
                q.OrderAsc(ViewState["sortDirection"].ToString());
            }
            else
            {
                if(ViewState["sortDirection"].ToString() == "ASC")
                {
                    q.OrderAsc(ViewState["sortDirection"].ToString());
                }
                else
                {
                    q.OrderDesc(ViewState["sortDirection"].ToString());
                }
            }
            
        }
        GridView1.DataSource = q.ExecuteDataSet();
        int startIndex;
        startIndex = GridView1.PageIndex * GridView1.PageSize;
        GridView1.PageIndex = e.NewPageIndex;
        GridView1.DataBind();
    }
    string SupplierNum(int id)
    {
        Query q=new Query("vw_orderdetail");
        q.AddWhere("CustomerID", id);
        q.AddWhere("status", 0);
        q.SetSelectList("suppliername");
        q.DISTINCT();
        return q.GetRecordCount().ToString();
    }
    protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
    {
        ViewState["sortColumn"] = e.SortExpression.ToString();
        if (ViewState["sortDirection"] == null)
        {
            ViewState["sortDirection"] = "ASC";
        }

        Panel1.Visible = true;
        SqlQuery q = new SqlQuery();
        q.From("vw_supplierinfodetail");
        q.AndExpression("TypeID").IsEqualTo(ddlIsType.SelectedValue);
        if (DDLcityID.SelectedValue != "0")
        {
            q.AndExpression("cityid").IsEqualTo(DDLcityID.SelectedValue);
        }
        if (DDLDistrictID.SelectedValue != "0")
        {
            q.AndExpression("districtID").IsEqualTo(DDLDistrictID.SelectedValue);
        }
        if (DDLcatalog.SelectedValue != "0")
        {
            q.AndExpression("catalogID").IsEqualTo(DDLcatalog.SelectedValue);
        }
        if (ddlDangCi.SelectedValue != "0")
        {
            q.AndExpression("dangciid").IsEqualTo(ddlDangCi.SelectedValue);
        }
        q.AndExpression("numready").IsGreaterThan(0);
        if (tbID.Text != "")
        {
            q.AndExpression("ID").IsEqualTo(tbID.Text);
        }
        if (tbSuppliername.Text != "")
        {
            q.AndExpression("suppliername").Like("%" + tbSuppliername.Text + "%");
        }
        if ("ASC" == ViewState["sortDirection"].ToString())
        {
            ViewState["sortDirection"] = "DESC";
            q.OrderDesc(e.SortExpression.ToString());
        }
        else
        {
            ViewState["sortDirection"] = "ASC";
            q.OrderAsc(e.SortExpression.ToString());

        }
        GridView1.DataSource = q.ExecuteDataSet();
        GridView1.DataBind();
    }
}
